<template>
  <el-form ref="form" :model="form" :rules="rules" label-width="100px">
    <el-form-item label="部门名称" prop="name">
      <el-input v-model="form.name" placeholder="1-5个字符" />
    </el-form-item>
    <el-form-item label="部门编码" prop="code">
      <el-input v-model="form.code" placeholder="1-5个字符" />
    </el-form-item>
    <el-form-item label="部门负责人" prop="manager">
      <el-select v-model="form.manager" placeholder="请选择部门负责人">
        <el-option
          v-for="item in peoples"
          :key="item.id"
          :value="item.username"
          :label="item.username"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="部门介绍" prop="introduce">
      <el-input v-model="form.introduce" prop="introduce" type="textarea" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit">确定</el-button>
      <el-button @click="onclose">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { getEmployeeSimple } from '@/api/employees'
import {
  addDepartments, // 添加
  getDepartDetail, // 获取详情
  updateDepartments// 更新
} from '@/api/departments'
export default {
  props: {
    pid: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    existedCodeList: {
      type: Array,
      required: true
    },
    cExistedNameList: {
      type: Array,
      required: true
    }
  },
  data() { //              采用的规则   被校验的值
    const validCode = (rule, value, callback) => {
      // console.log('当前要校验的值', value)
      // console.log('当前已经被占用code是', this.codeList, value)
      // if (this.codeList.includes(value)) {
      //   callback(new Error(`部门编码 ${value} 被占用`))
      // } else {
      //   callback()
      // }
      // 如果校验的值是existedCodeList里面有的编码,则验证不能通过
      console.log('code编码', this.existedCodeList) // this.existedCodeList,this指向问题,应该function换为箭头函数
      // console.log('当前输入的value要被校验的编码', value)
      // 第一种写法
      // if (this.isEdit) {
      //   const list = this.existedCodeList.filter(item => item !== this._code)
      //   console.log('当前除了点击的外的编码', list)
      //   list.includes(value)
      //     ? callback(new Error(`${value}  编码已经被占用`))
      //     : callback()
      // } else {
      //   this.existedCodeList.includes(value)
      //     ? callback(new Error(`${value}  编码已经被占用`))
      //     : callback()
      // }

      // 第二种写法(优化版)
      // 如果是编辑,则是15种编码 list是this.existedCodeList.filter(item => item !== this._code)
      // 否则,是16种this.existedCodeList
      const list = this.isEdit
        ? this.existedCodeList.filter(item => item !== this._code)
        : this.existedCodeList
      list.includes(value)
        ? callback(new Error(`${value}  编码已经被占用`))
        : callback()
    }
    const validName = (rule, value, callback) => {
      const list = this.isEdit
        ? this.cExistedNameList.filter(item => item !== this._name)
        : this.cExistedNameList
      list.includes(value)
        ? callback(new Error(`名字被占用${value}`))
        : callback()
    }
    return {
      peoples: [], // 保存部门负责人信息
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
        // pid:
      },
      rules: {
        name: [
          {
            required: true,
            message: '请输入部门名称',
            trigger: ['blur', 'change']
          },
          {
            min: 1,
            max: 20,
            message: '长度在 1到 20 个字符',
            trigger: ['blur', 'change']
          },
          { validator: validName, trigger: ['blur', 'change'] }
        ],
        code: [
          {
            required: true,
            message: '请选择部门编码',
            trigger: ['blur', 'change']
          },
          {
            min: 1,
            max: 20,
            message: '长度在 1到 20 个字符',
            trigger: ['blur', 'change']
          },
          { validator: validCode, trigger: ['blur', 'change'] }
        ],
        manager: [
          {
            required: true,
            message: '请选择部门负责人',
            trigger: ['blur', 'change']
          }
        ],
        introduce: [
          {
            required: true,
            message: '请输入部门介绍',
            trigger: ['blur', 'change']
          },
          {
            min: 1,
            max: 20,
            message: '长度在 1到 20 个字符',
            trigger: ['blur', 'change']
          }
        ]
      }
    }
  },
  async created() {
    this.loadEmployee()
    if (this.isEdit) {
      const res = await getDepartDetail(this.pid)
      this.form = res.data
      // console.log('修改后的页面', res)
      // 如果进入子组件后,发现是编辑页面,先把当前编码保存,在校验里要把不能使用的部门编号去除掉
      // 因为res.data.code数据能改动,单独找个_code接
      this._code = res.data.code
      console.log('获取到当前编码', res.data.code)
      this._name = res.data.name
    }
  },
  methods: {
    onSubmit() {
      this.$refs.form.validate((valid) => {
        // if (valid) {
        //   console.log('submit')
        //   if (this.isEdit) {
        //     this.doEdit() // 做编辑
        //   } else {
        //     this.doAdd() // 做添加
        //   }
        // } else {
        //   alert('error')
        // }
        if (!valid) {
          alert('error')
          return
        }
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    onclose() {
      this.$emit('closeFn')
    },
    async loadEmployee() {
      const res = await getEmployeeSimple()
      // console.log('员工基本信息简单列表', res)
      this.peoples = res.data
    },
    async doAdd() {
      const res = await addDepartments({ ...this.form, pid: this.pid })
      console.log('新增部门列表', res)
      this.$emit('update-depart')
    },
    async doEdit() {
      const res = await updateDepartments(this.form)
      console.log('编辑操作的返回结果', res)
      this.$emit('update-depart')
    }
  }
}

</script>

<style>
</style>
